<template>
	<div class="content">
		<common-head :showIcon="false" :showBackButton="true"></common-head>
		<div class="container">
			<div class="form-container">
				<!-- 消息类型选择 -->
				<div class="form-item">
					<label>消息类型：</label>
					<van-field v-model="errorTypeLabel" readonly clickable placeholder="请选择消息类型"
						@click="showTypePicker = true" right-icon="arrow-down" />
					<van-popup v-model:show="showTypePicker" position="bottom">
						<van-picker show-toolbar :columns="typeOptions" @confirm="onTypeConfirm"
							@cancel="showTypePicker = false" />
					</van-popup>
				</div>

				<!-- 通用字段 -->
				<div class="form-item">
					<label>停车场选择：</label>
					<van-field v-model="selectedParkingText" readonly clickable placeholder="请选择停车场"
						@click="showParkingPicker = true" right-icon="arrow-down" />
					<van-popup v-model:show="showParkingPicker" position="bottom">
						<van-picker show-toolbar :columns="parkingOptions" @confirm="onParkingConfirm"
							@cancel="showParkingPicker = false" />
					</van-popup>
				</div>
				<div class="form-item">
					<label>泊位选择：</label>
					<van-field v-model="selectedBerthText" readonly clickable placeholder="请选择泊位" @click="onBerthClick"
						right-icon="arrow-down" />
					<van-popup v-model:show="showBerthPicker" position="bottom">
						<van-picker show-toolbar :columns="berthOptions" @confirm="onBerthConfirm"
							@cancel="showBerthPicker = false" />
					</van-popup>
				</div>

				<!-- 动态字段 -->
				<template v-if="formData.errorType === '10'">
					<div class="form-item">
						<label>入场时间：</label>
						<div class="time-picker">
							<!-- 年 -->
							<van-field v-model="startYear" readonly clickable @click="showStartYearPicker = true"
								right-icon="arrow-down" />
							年
							<van-popup v-model:show="showStartYearPicker" position="bottom">
								<van-picker show-toolbar :columns="yearOptions" @confirm="onStartYearConfirm"
									@cancel="showStartYearPicker = false" />
							</van-popup>

							<!-- 月 -->
							<van-field v-model="startMonth" readonly clickable @click="showStartMonthPicker = true"
								right-icon="arrow-down" />
							月
							<van-popup v-model:show="showStartMonthPicker" position="bottom">
								<van-picker show-toolbar :columns="monthOptions" @confirm="onStartMonthConfirm"
									@cancel="showStartMonthPicker = false" />
							</van-popup>

							<!-- 日 -->
							<van-field v-model="startDay" readonly clickable @click="showStartDayPicker = true"
								right-icon="arrow-down" />
							日
							<van-popup v-model:show="showStartDayPicker" position="bottom">
								<van-picker show-toolbar :columns="dayOptions" @confirm="onStartDayConfirm"
									@cancel="showStartDayPicker = false" />
							</van-popup>
						</div>
						<div class="time-picker">
							<!-- 时 -->
							<van-field v-model="startHour" readonly clickable @click="showStartHourPicker = true"
								right-icon="arrow-down" />
							时
							<van-popup v-model:show="showStartHourPicker" position="bottom">
								<van-picker show-toolbar :columns="hourOptions" @confirm="onStartHourConfirm"
									@cancel="showStartHourPicker = false" />
							</van-popup>

							<!-- 分 -->
							<van-field v-model="startMinute" readonly clickable @click="showStartMinutePicker = true"
								right-icon="arrow-down" />
							分
							<van-popup v-model:show="showStartMinutePicker" position="bottom">
								<van-picker show-toolbar :columns="minuteOptions" @confirm="onStartMinuteConfirm"
									@cancel="showStartMinutePicker = false" />
							</van-popup>

							<!-- 秒 -->
							<van-field v-model="startSecond" readonly clickable @click="showStartSecondPicker = true"
								right-icon="arrow-down" />
							秒
							<van-popup v-model:show="showStartSecondPicker" position="bottom">
								<van-picker show-toolbar :columns="secondOptions" @confirm="onStartSecondConfirm"
									@cancel="showStartSecondPicker = false" />
							</van-popup>
						</div>
					</div>
					<div class="form-item">
						<label>订单ID：</label>
						<van-field v-model="formData.orderId" placeholder="请输入订单ID" />
					</div>
					<div class="form-item">
						<label>是否出场：</label>
						<van-radio-group v-model="formData.exitStatus" direction="horizontal">
							<van-radio name="0">未出场</van-radio>
							<van-radio name="1">已出场</van-radio>
						</van-radio-group>
					</div>
					<div class="form-item" v-if="formData.exitStatus === '1'">
						<label>出场时间：</label>
						<div class="time-picker">
							<!-- 年 -->
							<van-field v-model="endYear" readonly clickable @click="showEndYearPicker = true"
								right-icon="arrow-down" />
							年
							<van-popup v-model:show="showEndYearPicker" position="bottom">
								<van-picker show-toolbar :columns="yearOptions" @confirm="onEndYearConfirm"
									@cancel="showEndYearPicker = false" />
							</van-popup>

							<!-- 月 -->
							<van-field v-model="endMonth" readonly clickable @click="showEndMonthPicker = true"
								right-icon="arrow-down" />
							月
							<van-popup v-model:show="showEndMonthPicker" position="bottom">
								<van-picker show-toolbar :columns="monthOptions" @confirm="onEndMonthConfirm"
									@cancel="showEndMonthPicker = false" />
							</van-popup>

							<!-- 日 -->
							<van-field v-model="endDay" readonly clickable @click="showEndDayPicker = true"
								right-icon="arrow-down" />
							日
							<van-popup v-model:show="showEndDayPicker" position="bottom">
								<van-picker show-toolbar :columns="dayOptions" @confirm="onEndDayConfirm"
									@cancel="showEndDayPicker = false" />
							</van-popup>
						</div>
						<div class="time-picker">
							<!-- 时 -->
							<van-field v-model="endHour" readonly clickable @click="showEndHourPicker = true"
								right-icon="arrow-down" />
							时
							<van-popup v-model:show="showEndHourPicker" position="bottom">
								<van-picker show-toolbar :columns="hourOptions" @confirm="onEndHourConfirm"
									@cancel="showEndHourPicker = false" />
							</van-popup>

							<!-- 分 -->
							<van-field v-model="endMinute" readonly clickable @click="showEndMinutePicker = true"
								right-icon="arrow-down" />
							分
							<van-popup v-model:show="showEndMinutePicker" position="bottom">
								<van-picker show-toolbar :columns="minuteOptions" @confirm="onEndMinuteConfirm"
									@cancel="showEndMinutePicker = false" />
							</van-popup>

							<!-- 秒 -->
							<van-field v-model="endSecond" readonly clickable @click="showEndSecondPicker = true"
								right-icon="arrow-down" />
							秒
							<van-popup v-model:show="showEndSecondPicker" position="bottom">
								<van-picker show-toolbar :columns="secondOptions" @confirm="onEndSecondConfirm"
									@cancel="showEndSecondPicker = false" />
							</van-popup>
						</div>
					</div>
				</template>

				<template v-else-if="formData.errorType === '40'">
					<div class="form-item">
						<label>设备编码：</label>
						<van-field v-model="formData.deviceCode" placeholder="请输入设备编码" />
					</div>
					<div class="form-item">
						<label>设备类型：</label>
						<van-field v-model="selectDeviceText" readonly clickable placeholder="请选择设备类型"
							@click="showDeviceTypePicker = true" right-icon="arrow-down" />
						<van-popup v-model:show="showDeviceTypePicker" position="bottom">
							<van-picker show-toolbar :columns="deviceTypeOptions" @confirm="onDeviceTypeConfirm"
								@cancel="showDeviceTypePicker = false" />
						</van-popup>
					</div>
					<div class="form-item">
						<label>异常内容：</label>
						<van-field v-model="formData.errorContent" placeholder="请输入异常内容" />
					</div>
<!-- 					<div class="form-item">
						<label>处理描述：</label>
						<van-field v-model="formData.handlingMethod" placeholder="请输入处理描述" />
					</div> -->
				</template>

				<template v-else-if="['20','30'].includes(formData.errorType)">
					<div class="form-item">
						<label>车牌号码：</label>
						<van-field v-model="formData.carNumber" placeholder="请输入车牌号码" />
					</div>
					<div class="form-item">
						<label>入场时间：</label>
						<div class="time-picker">
							<!-- 年 -->
							<van-field v-model="startYear" readonly clickable @click="showStartYearPicker = true"
								right-icon="arrow-down" />
							年
							<van-popup v-model:show="showStartYearPicker" position="bottom">
								<van-picker show-toolbar :columns="yearOptions" @confirm="onStartYearConfirm"
									@cancel="showStartYearPicker = false" />
							</van-popup>

							<!-- 月 -->
							<van-field v-model="startMonth" readonly clickable @click="showStartMonthPicker = true"
								right-icon="arrow-down" />
							月
							<van-popup v-model:show="showStartMonthPicker" position="bottom">
								<van-picker show-toolbar :columns="monthOptions" @confirm="onStartMonthConfirm"
									@cancel="showStartMonthPicker = false" />
							</van-popup>

							<!-- 日 -->
							<van-field v-model="startDay" readonly clickable @click="showStartDayPicker = true"
								right-icon="arrow-down" />
							日
							<van-popup v-model:show="showStartDayPicker" position="bottom">
								<van-picker show-toolbar :columns="dayOptions" @confirm="onStartDayConfirm"
									@cancel="showStartDayPicker = false" />
							</van-popup>
						</div>
						<div class="time-picker">
							<!-- 时 -->
							<van-field v-model="startHour" readonly clickable @click="showStartHourPicker = true"
								right-icon="arrow-down" />
							时
							<van-popup v-model:show="showStartHourPicker" position="bottom">
								<van-picker show-toolbar :columns="hourOptions" @confirm="onStartHourConfirm"
									@cancel="showStartHourPicker = false" />
							</van-popup>

							<!-- 分 -->
							<van-field v-model="startMinute" readonly clickable @click="showStartMinutePicker = true"
								right-icon="arrow-down" />
							分
							<van-popup v-model:show="showStartMinutePicker" position="bottom">
								<van-picker show-toolbar :columns="minuteOptions" @confirm="onStartMinuteConfirm"
									@cancel="showStartMinutePicker = false" />
							</van-popup>

							<!-- 秒 -->
							<van-field v-model="startSecond" readonly clickable @click="showStartSecondPicker = true"
								right-icon="arrow-down" />
							秒
							<van-popup v-model:show="showStartSecondPicker" position="bottom">
								<van-picker show-toolbar :columns="secondOptions" @confirm="onStartSecondConfirm"
									@cancel="showStartSecondPicker = false" />
							</van-popup>
						</div>
					</div>
					<div class="form-item" v-if="formData.exitStatus === '1'">
						<label>出场时间：</label>
						<div class="time-picker">
							<!-- 年 -->
							<van-field v-model="endYear" readonly clickable @click="showEndYearPicker = true"
								right-icon="arrow-down" />
							年
							<van-popup v-model:show="showEndYearPicker" position="bottom">
								<van-picker show-toolbar :columns="yearOptions" @confirm="onEndYearConfirm"
									@cancel="showEndYearPicker = false" />
							</van-popup>

							<!-- 月 -->
							<van-field v-model="endMonth" readonly clickable @click="showEndMonthPicker = true"
								right-icon="arrow-down" />
							月
							<van-popup v-model:show="showEndMonthPicker" position="bottom">
								<van-picker show-toolbar :columns="monthOptions" @confirm="onEndMonthConfirm"
									@cancel="showEndMonthPicker = false" />
							</van-popup>

							<!-- 日 -->
							<van-field v-model="endDay" readonly clickable @click="showEndDayPicker = true"
								right-icon="arrow-down" />
							日
							<van-popup v-model:show="showEndDayPicker" position="bottom">
								<van-picker show-toolbar :columns="dayOptions" @confirm="onEndDayConfirm"
									@cancel="showEndDayPicker = false" />
							</van-popup>
						</div>
						<div class="time-picker">
							<!-- 时 -->
							<van-field v-model="endHour" readonly clickable @click="showEndHourPicker = true"
								right-icon="arrow-down" />
							时
							<van-popup v-model:show="showEndHourPicker" position="bottom">
								<van-picker show-toolbar :columns="hourOptions" @confirm="onEndHourConfirm"
									@cancel="showEndHourPicker = false" />
							</van-popup>

							<!-- 分 -->
							<van-field v-model="endMinute" readonly clickable @click="showEndMinutePicker = true"
								right-icon="arrow-down" />
							分
							<van-popup v-model:show="showEndMinutePicker" position="bottom">
								<van-picker show-toolbar :columns="minuteOptions" @confirm="onEndMinuteConfirm"
									@cancel="showEndMinutePicker = false" />
							</van-popup>

							<!-- 秒 -->
							<van-field v-model="endSecond" readonly clickable @click="showEndSecondPicker = true"
								right-icon="arrow-down" />
							秒
							<van-popup v-model:show="showEndSecondPicker" position="bottom">
								<van-picker show-toolbar :columns="secondOptions" @confirm="onEndSecondConfirm"
									@cancel="showEndSecondPicker = false" />
							</van-popup>
						</div>
					</div>
					<div class="form-item">
						<label>历史欠费金额：</label>
						<van-field v-model="formData.arrearAmount" type="number" placeholder="请输入金额" />
					</div>
					<div class="form-item">
						<label>续交费用：</label>
						<van-field v-model="formData.renewalFee" type="number" placeholder="请输入费用" />
					</div>
					<div class="form-item">
						<label>车辆类型：</label>
						<van-field v-model="formData.plateTypeLabel" readonly clickable placeholder="请选择车辆类型"
							@click="showPlateTypePicker = true" right-icon="arrow-down" />
						<van-popup v-model:show="showPlateTypePicker" position="bottom">
							<van-picker show-toolbar :columns="plateTypeOptions" @confirm="onPlateTypeConfirm"
								@cancel="showPlateTypePicker = false" />
						</van-popup>
					</div>
				</template>

				<!-- 提交按钮 -->
				<div class="form-item">
					<van-button :color="isFormValid ? 'rgb(47,111,226)' : '#aaa'" :disabled="!isFormValid" block
						@click="submitForm">
						<span :style="{ color: isFormValid ? 'white' : '#666', fontWeight: 'bold' }">
							提交消息
						</span>
					</van-button>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import commonHead from "../../components/xc/commonHead.vue";

	export default {
		components: {
			commonHead
		},
		data() {
			const now = new Date();
			return {
				showTypePicker: false,
				showParkingPicker: false,
				showBerthPicker: false,
				showDeviceTypePicker: false,
				showPlateTypePicker: false,

				// 入场时间字段
				startYear: now.getFullYear(),
				startMonth: now.getMonth() + 1,
				startDay: now.getDate(),
				startHour: now.getHours(),
				startMinute: now.getMinutes(),
				startSecond: now.getSeconds(),

				// 出场时间字段
				endYear: now.getFullYear(),
				endMonth: now.getMonth() + 1,
				endDay: now.getDate(),
				endHour: now.getHours(),
				endMinute: now.getMinutes(),
				endSecond: now.getSeconds(),

				// 控制显示状态
				showStartYearPicker: false,
				showStartMonthPicker: false,
				showStartDayPicker: false,
				showStartHourPicker: false,
				showStartMinutePicker: false,
				showStartSecondPicker: false,

				showEndYearPicker: false,
				showEndMonthPicker: false,
				showEndDayPicker: false,
				showEndHourPicker: false,
				showEndMinutePicker: false,
				showEndSecondPicker: false,

				formData: {
					errorType: '',
					parkingId: '',
					carportCode: '',
					// 各类型独有字段
					startTime: '',
					orderId: '',
					exitStatus: '0',
					endTime: '',
					deviceCode: '',
					deviceType: '',
					errorContent: '',
					// handlingMethod: '',
					carNumber: '',
					arrearAmount: '',
					renewalFee: '',
					plateType: ''
				},

				// 选择器选项
				typeOptions: [{
						text: '无牌车入场',
						value: '10'
					},
					{
						text: '欠费车入场',
						value: '20'
					},
					{
						text: '僵尸车',
						value: '30'
					},
					{
						text: '设备异常',
						value: '40'
					}
				],
				deviceTypeOptions: [{
						text: '摄像头',
						value: '10'
					},
					{
						text: '地锁',
						value: '20'
					}
				],
				plateTypeOptions: [{
						text: '临停',
						value: '10'
					},
					{
						text: '月卡用户',
						value: '20'
					},
					{
						text: '年卡用户',
						value: '30'
					},
					{
						text: 'VIP',
						value: '40'
					}
				],

				// 停车场相关
				parkingOptions: [],
				berthOptions: [],
				selectedParkingText: "", // 选中的停车点位显示文本
				selectedBerthText: "", // 选中的泊位显示文本
				selectDeviceText: "",  //选择设备名称

			};
		},
		computed: {
			errorTypeLabel() {
				const foundItem = this.typeOptions.find(item => item.value === this.formData.errorType);
				return foundItem ? foundItem.text : '';
			},
			// 基础校验
			isFormValid() {
				if (!this.formData.errorType || !this.formData.parkingId || !this.formData.carportCode) return false

				// 类型相关校验（使用实际字段值）
				switch (this.formData.errorType) {
					case '10':
						return !!this.formattedStartTime &&
							!!this.formData.orderId &&
							(this.formData.exitStatus === '0' ||
								(this.formData.exitStatus === '1' && !!this.formattedEndTime))

					case '40':
						return !!this.formData.deviceCode &&
							!!this.formData.deviceType &&
							!!this.formData.errorContent 

					case '20':
					case '30':
						return !!this.formData.carNumber &&
							!!this.formattedStartTime &&
							!!this.formattedEndTime &&
							!!this.formData.arrearAmount &&
							!!this.formData.plateType // 直接验证plateType字段

					default:
						return false
				}
			},
			// 生成时间选项（与orderInfo.vue保持一致）
			yearOptions() {
				return this.generateOptions(2020, 2030);
			},
			monthOptions() {
				return this.generateOptions(1, 12, true);
			},
			dayOptions() {
				return this.generateOptions(1, 31, true);
			},
			hourOptions() {
				return this.generateOptions(0, 23, true);
			},
			minuteOptions() {
				return this.generateOptions(0, 59, true);
			},
			secondOptions() {
				return this.generateOptions(0, 59, true);
			},

			formattedStartTime() {
				return `${this.startYear}-${this.padZero(this.startMonth)}-${this.padZero(this.startDay)} ` +
					`${this.padZero(this.startHour)}:${this.padZero(this.startMinute)}:${this.padZero(this.startSecond)}`;
			},
			formattedEndTime() {
				return `${this.endYear}-${this.padZero(this.endMonth)}-${this.padZero(this.endDay)} ` +
					`${this.padZero(this.endHour)}:${this.padZero(this.endMinute)}:${this.padZero(this.endSecond)}`;
			}
		},
		methods: {
			padZero(num) {
				return num.toString().padStart(2, '0');
			},

			// 时间处理方法（示例）
			generateOptions(start, end, pad = false) {
				return Array.from({
					length: end - start + 1
				}, (_, i) => ({
					text: pad ? `${i + start}`.padStart(2, '0') : `${i + start}`,
					value: i + start
				}));
			},

			// 入场时间确认
			onStartYearConfirm(value) {
				this.startYear = value.value;
				this.showStartYearPicker = false;
			},

			onStartMonthConfirm(value) {
				this.startMonth = value.value;
				this.showStartMonthPicker = false;
			},

			onStartDayConfirm(value) {
				this.startDay = value.value;
				this.showStartDayPicker = false;
			},

			onStartHourConfirm(value) {
				this.startHour = value.value;
				this.showStartHourPicker = false;
			},

			onStartMinuteConfirm(value) {
				this.startMinute = value.value;
				this.showStartMinutePicker = false;
			},

			onStartSecondConfirm(value) {
				this.startSecond = value.value;
				this.showStartSecondPicker = false;
			},

			// 出场时间确认
			onEndYearConfirm(value) {
				this.endYear = value.value;
				this.showEndYearPicker = false;
			},

			onEndMonthConfirm(value) {
				this.endMonth = value.value;
				this.showEndMonthPicker = false;
			},

			onEndDayConfirm(value) {
				this.endDay = value.value;
				this.showEndDayPicker = false;
			},

			onEndHourConfirm(value) {
				this.endHour = value.value;
				this.showEndHourPicker = false;
			},

			onEndMinuteConfirm(value) {
				this.endMinute = value.value;
				this.showEndMinutePicker = false;
			},

			onEndSecondConfirm(value) {
				this.endSecond = value.value;
				this.showEndSecondPicker = false;
			},
			// 类型选择
			onTypeConfirm(value) {
				this.formData.errorType = value.value
				this.showTypePicker = false
				this.clearDynamicFields()
			},

			// 停车场选择（参考orderInfo.vue）
			async getParkingList() {
				try {
					const res = await this.baseService.get('/parking/bizParkingLots/queryList?parkingType=20')
					this.parkingOptions = res.result.map(item => ({
						text: item.parkingName,
						value: item.id
					}))
				} catch (error) {
					this.$toast("获取停车场失败")
				}
			},
			onParkingConfirm(value) {
				this.formData.parkingId = value.value
				this.selectedParkingText = value.text
				this.showParkingPicker = false
				this.getBerthList()
			},

			// 泊位选择（参考orderInfo.vue）
			async getBerthList() {
				try {
					const res = await this.baseService.get(
						`/parking/parkingCarPort/list?parkingId=${this.formData.parkingId}`)
					this.berthOptions = res.result.map(item => ({
						text: item.code,
						value: item.id
					}))
				} catch (error) {
					this.$toast("获取泊位列表失败")
				}
			},
			// 泊位选择点击事件
			onBerthClick() {
				if (!this.selectedParkingText) {
					this.$toast("请先选择停车点");
				} else {
					this.showBerthPicker = true;
				}
			},
			onBerthConfirm(value) {
				this.formData.carportCode = value.value
				this.selectedBerthText = value.text
				this.showBerthPicker = false
			},

			// 其他选择器
			onDeviceTypeConfirm(value) {
				this.formData.deviceType = value.value
				this.selectDeviceText = value.text
				this.showDeviceTypePicker = false
			},
			onPlateTypeConfirm(value) {
				this.formData.plateType = value.value
				this.formData.plateTypeLabel = value.text
				this.showPlateTypePicker = false
			},

			// 清除动态字段
			clearDynamicFields() {
				Object.keys(this.formData).forEach(key => {
					if (!['errorType', 'parkingId', 'carportCode'].includes(key)) {
						this.formData[key] = ''
					}
				})
			},

			// 提交表单
			async submitForm() {
				try {
					if (this.isFormValid) {
						if (this.formData.errorType === '10') {
							this.formData.startTime = this.formattedStartTime;
						}
						if (this.formData.exitStatus === '1' && this.formData.errorType === '10') {
							this.formData.endTime = this.formattedEndTime;
						}
						if (['20', '30'].includes(this.formData.errorType)) {
							this.formData.startTime = this.formattedStartTime;
							this.formData.endTime = this.formattedEndTime;
						}
						// 这里可以添加提交表单的逻辑
						const res = await this.baseService.post('/parking/bizParkingError/add', this.formData)
						if (res.code === 200) {
							this.$toast.success('新增成功')
							this.$router.go(-1)
						} else {
							this.$toast.fail(res.message)
						}
					}
				} catch (error) {
					this.$toast.fail('提交失败')
				}
			},

			formatDate(dateStr) {
				return new Date(dateStr).toISOString().replace('T', ' ').substring(0, 19)
			}
		},
		mounted() {
			this.getParkingList()
		}
	};
</script>

<style lang="less" scoped>
	.time-picker {
		display: flex;
		align-items: center;
		gap: 8px;
		margin-bottom: 10px;

		.van-field {
			width: 80px;
			padding: 6px;
			background: #f5f5f5;
			border-radius: 4px;
		}
	}

	/* 保持与orderInfo.vue一致的样式 */
	.content {
		height: 100vh;
		background-image: linear-gradient(to right, #cee7ff, #a5d3ff);
	}

	.container {
		padding: 10px;
		height: calc(100% - 46px);
	}

	.form-container {
		background: white;
		border-radius: 8px;
		padding: 15px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

		.form-item {
			margin-bottom: 15px;

			label {
				display: block;
				margin-bottom: 8px;
				font-size: 14px;
				color: #666;
			}

			.van-field {
				background: #f5f5f5;
				border-radius: 4px;
				padding: 8px 12px;
			}

			.van-radio-group {
				padding: 8px 0;

				.van-radio {
					margin-right: 20px;
				}
			}
		}

		.van-button {
			margin-top: 20px;
			border-radius: 4px;
		}
	}
</style>